from django.http import HttpResponse, JsonResponse
from rest_framework.response import Response
from XMock.utils import response_mock

from XApiTestServer.models import MockInfo
from XApiTestServer.utils.common import *

import logging


logger = logging.getLogger('XMock')


def mock_response(request, mock_url):
    """
    mock定制response
    :param request:
    :param mock_url: mock url
    :return:
    """
    mock_url = mock_url
    mock_method = request.method
    # kwargs = json.loads(request.body.decode('utf-8'))
    logger.info('Mock Request Info : Request Method-{mock_method} , Request URL-{mock_url}'.format(
        mock_method=mock_method, mock_url=mock_url))

    if mock_url is None:
        logger.error('Mock Request URL is empty.')
        return JsonResponse(response_mock.MOCK_URL_NOT_FOUND,json_dumps_params={'ensure_ascii':False})

    mock_info_list = MockInfo.objects.filter(mock_url__exact=mock_url, request_method__exact=mock_method).values(
        'request_method', 'mock_url', 'response_body')

    if len(mock_info_list) == 1:
        mock_response = eval(mock_info_list[0]['response_body'])
        logger.info('Mock Response Info : {mock_response}'.format(mock_response=mock_response))
        return JsonResponse(mock_response,json_dumps_params={'ensure_ascii':False})
    elif len(mock_info_list) == 0:
        logger.error('Mock Request Method-{mock_method} URL-{mock_url} not exist.'.format(mock_method=mock_method, mock_url=mock_url))
        return JsonResponse(response_mock.MOCK_DATA_NOT_EXIST,json_dumps_params={'ensure_ascii':False})
    else:
        return JsonResponse(response_mock.MOCK_DATA_MORE_THAN_ONE,json_dumps_params={'ensure_ascii':False})
